package com.material.common.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.common.comm.ResponseMessage;
import com.aliyun.oss.model.GenericRequest;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutBucketImageRequest;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.VoidResult;
import com.material.common.config.AliOssProperties;

import java.io.InputStream;

/**
 * @author ganxinge
 */
public class OssClientUtil {
    private static OSS ossClient;
    public static OSS getOSSClient() {
        if (ossClient == null) {
            ossClient = new OSSClientBuilder().build(AliOssProperties.ENDPOINT, AliOssProperties.ACCESS_KEY_ID, AliOssProperties.ACCESS_KEY_SECRET);
        }
        return ossClient;
    }

    private static void closeOSSClient() {
        if (ossClient != null) {
            ossClient.shutdown();
            ossClient = null;
        }
    }

    public static String uploadFile(String fileName, InputStream inputStream){
        OSS ossClient = OssClientUtil.getOSSClient();
        PutObjectRequest putObjectRequest = new PutObjectRequest(AliOssProperties.BUCKET_NAME, fileName, inputStream);
        // 上传文件
        ossClient.putObject(putObjectRequest);
        // 关闭 OSS 客户端
        closeOSSClient();
        // 返回访问链接
        String url = AliOssProperties.DOMAIN_URL + fileName;
        return url;
    }

    public static String uploadImage(String fileName, InputStream inputStream){
        ObjectMetadata metadata = new ObjectMetadata();
        // 设置正确的 Content-Type
        metadata.setContentType("image/jpeg");
        // 设置为 inline 以避免下载
        metadata.setContentDisposition("inline");
        OSS ossClient = OssClientUtil.getOSSClient();
        PutObjectRequest putObjectRequest = new PutObjectRequest(AliOssProperties.BUCKET_NAME, fileName, inputStream);
        putObjectRequest.setMetadata(metadata);
        // 上传文件
        ossClient.putObject(putObjectRequest);
        // 关闭 OSS 客户端
        closeOSSClient();
        // 返回访问链接
        String url = AliOssProperties.DOMAIN_URL + fileName;
        return url;
    }

    public static boolean deleteFile(String objectKey){
        OSS ossClient = OssClientUtil.getOSSClient();
        if(objectKey.startsWith(AliOssProperties.DOMAIN_URL)){
            objectKey = objectKey.replace(AliOssProperties.DOMAIN_URL, "");
        }
        GenericRequest genericRequest = new GenericRequest(AliOssProperties.BUCKET_NAME,objectKey);
        VoidResult voidResult = ossClient.deleteObject(genericRequest);
        ResponseMessage response = voidResult.getResponse();
        int statusCode = response.getStatusCode();
        closeOSSClient();
        return true;
    }

}
